package com.chatgpt.base.utils;

import com.alibaba.fastjson.JSON;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具
 *
 * @author yangjian
 */
public class StringUtil
{

    /**
     * 生成随机字符串
     *
     * @param length 字符串长度
     * @return 返回随机字符串
     */
    public static String generateRandomString(int length)
    {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKMNLOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 生成一个随机数字字符串
     * Attention : The maximum length is 16
     *
     * @param length 字符串长度
     * @return 返回数字字符串
     */
    public static String generateRandomNumber(int length)
    {
        if (length > 16) {
            throw new IndexOutOfBoundsException("Can not generate more than 16 bit string");
        }
        return (((Double) Math.random()).toString()).substring(2, length + 2);
    }

    /* 将对象转为 JSON 字符串 */
    public static String jsonEncode(Object obj)
    {
        return JSON.toJSONString(obj);
    }

    /* JSON 字符串还原为对象 */
    public static <T> T jsonDecode(String json, Class<T> clazz)
    {
        return JSON.parseObject(json, clazz);
    }

}
